<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="代理商名称" prop="agentName">
        <el-input
          v-model="queryParams.agentName"
          placeholder="请输入代理商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上级代理商名称" prop="parentName">
        <el-input
          v-model="queryParams.parentName"
          placeholder="请输入上级代理商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker clearable
          v-model="queryParams.startDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker clearable
          v-model="queryParams.endDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:agent:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:agent:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:agent:export']"
        >导出</el-button>
      </el-col> -->
    </el-row>

    <el-table v-loading="loading" :data="agentList" @selection-change="handleSelectionChange">
      <el-table-column :formatter="defaultTableColumnDate" type="selection" width="55" align="center" />
      <el-table-column :formatter="defaultTableColumnDate" label="序列" type="index" align="center" />
      <el-table-column :formatter="defaultTableColumnDate" label="代理商名称" align="center" prop="agentName" />
      <el-table-column :formatter="defaultTableColumnDate" label="手机号" align="center" prop="phone" />
      <el-table-column :formatter="defaultTableColumnDate" label="佣金比例" align="center" prop="rate" />
      <el-table-column :formatter="defaultTableColumnDate" label="上级代理商名称" align="center" prop="parentName" />
      <el-table-column :formatter="defaultTableColumnDate" label="所在地区" align="center" prop="address" />
      <el-table-column :formatter="defaultTableColumnDate" label="专属链接" align="center" prop="link">
        <template slot-scope="scope">
          <el-link type="primary" @click="copyToClipboard(scope.row.link)">专属链接</el-link>
        </template>
      </el-table-column>
      <el-table-column :formatter="defaultTableColumnDate" label="专属小程序码" align="center" prop="programCode">
        <template slot-scope="scope">
          <el-image 
            style="width: 40px; height: 40px"
            :src="scope.row.programCode" 
            :preview-src-list="[scope.row.programCode]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column :formatter="defaultTableColumnDate" label="更新人" align="center" prop="updateUser" />
      <el-table-column :formatter="defaultTableColumnDate" label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :formatter="defaultTableColumnDate" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:agent:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:agent:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改代理商对话框 -->
    <el-dialog destroy-on-close :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="代理商名称" prop="agentName">
          <el-input v-model="form.agentName" placeholder="请输入代理商名称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入登录密码" />
        </el-form-item>
        <el-form-item label="所在地区" prop="address">
          <el-cascader
            v-model="form.address"
            placeholder="请选择"
            style="width: 100%;"
            :options="cityOptions"
            :props="{ checkStrictly: true, label: 'cityName', value: 'cityName', children: 'citys' }"
            clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="上级代理商" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择上级代理商" style="width: 100%;">
            <el-option
              v-for="item in agentIdList"
              :key="item.id"
              :label="item.agentName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="佣金比例" prop="rate">
          <el-input v-model="form.rate" placeholder="请输入佣金比例" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { agentList } from "@/api/system/enterpriseInfo";
import { listAgent, getAgent, delAgent, addAgent, updateAgent } from "@/api/system/agent";
import citys from '../../../utils/citys.json'

export default {
  name: "Agent",
  data() {
    return {
      cityOptions: citys.provinces,
      agentIdList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代理商表格数据
      agentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        agentName: null,
        phone: null,
        password: null,
        address: null,
        province: null,
        city: null,
        parentId: null,
        rate: null,
        link: null,
        programCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        agentName: [
          { required: true, trigger: "blur", message: "请输入代理商名称" }
        ],
        phone: [
          { required: true, trigger: "blur", message: "请输入手机号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入登录密码" }
        ],
        rate: [
          { required: true, trigger: "blur", message: "请输入佣金比例" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getAgentList()
  },
  methods: {
    getAgentList() {
      agentList({}).then(res => {
        this.agentIdList = res.data
      })
    },
    copyToClipboard(text) {
      const textarea = document.createElement('textarea');
      textarea.value = text;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
      this.$modal.msgSuccess("复制成功");
    },
    /** 查询代理商列表 */
    getList() {
      this.loading = true;
      listAgent(this.queryParams).then(response => {
        this.agentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        agentName: null,
        phone: null,
        password: null,
        address: null,
        province: null,
        city: null,
        parentId: null,
        rate: null,
        link: null,
        programCode: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加代理商";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAgent(id).then(response => {
        this.form = response.data;
        if(this.form.address) {
          this.form.address = response.data.address.split("-");
        }
        this.open = true;
        this.title = "修改代理商";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.address) {
            this.form.address = this.form.address.join('-')
          }
          if (this.form.id != null) {
            updateAgent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAgent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除代理商编号为"' + ids + '"的数据项？').then(function() {
        return delAgent(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/agent/export', {
        ...this.queryParams
      }, `agent_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
